#include "Engine.h"

dkm::Engine* dkm::Engine::instance = NULL;

dkm::Engine::Engine()
	:deviceToUse(0)
	,devices(std::vector<IDirect3DDevice9*>())
	,texNames(std::vector<string>())
	,allTex(std::vector<IDirect3DTexture9*>())
	,allComponents(std::vector<Component*>())
{

}

dkm::Engine::~Engine()
{
	CleanAllTex();
}

void dkm::Engine::Update(float dt)
{
	std::vector<Component*>::iterator iter = allComponents.begin();
	while (iter != allComponents.end())
	{
		if ((*iter)->GetActive())
		(*iter)->Update(dt);

		++iter;
	}
}

void dkm::Engine::Draw()
{
	HR(gd3dDevice->SetRenderState(D3DRS_ALPHATESTENABLE, true));

	std::vector<Component*>::iterator iter = allComponents.begin();
	while (iter != allComponents.end())
	{
		if ((*iter)->GetVisible())
		(*iter)->Draw();

		++iter;
	}

	HR(gd3dDevice->SetRenderState(D3DRS_ALPHATESTENABLE, false));
}

void dkm::Engine::AddComponent(dkm::Component* component)
{
	allComponents.push_back(component);
}

void dkm::Engine::RemoveComponent(dkm::Component* component)
{
	allComponents.erase(find(allComponents.begin(), allComponents.end(), component));
}

void dkm::Engine::AddDevice(IDirect3DDevice9* device, bool useNow)
{
	std::vector<IDirect3DDevice9*>::iterator iter = find(devices.begin(), devices.end(), device);
	if (!(iter != devices.end()))
	{
		devices.push_back(device);
		if (useNow) deviceToUse = devices.size() -1;
	}
	else
	{
		if (useNow) deviceToUse = iter - devices.begin();
	}
}

void dkm::Engine::RemoveDevice(IDirect3DDevice9* device)
{

}

void dkm::Engine::UseDevice(IDirect3DDevice9* device)
{

}

IDirect3DTexture9* dkm::Engine::AddTex(string texName)
{
	if (devices.size() == 0) return NULL;
	if (!FindTex(texName))
	{
		IDirect3DTexture9* texture;
		//LPCSTR texSrc(texName);
		D3DXCreateTextureFromFile(devices[deviceToUse], texName.c_str(), &texture);
		allTex.push_back(texture);
		texNames.push_back(texName);
		return texture;
	}
	else
	{
		return GetTex(texName);
	}
}

void dkm::Engine::RemoveTex(string texName)
{
	if (allTex.size() == 0) return;
	if (FindTex(texName))
	{
		allTex.erase(allTex.begin() + GetTexId(texName));
		texNames.erase(texNames.begin() + GetTexId(texName));
	}
}

bool dkm::Engine::FindTex(string texName)
{
	if (texNames.size() == 0) return false;
	return ( find(texNames.begin(), texNames.end(), texName) != texNames.end() );
}

int dkm::Engine::GetTexId(string texName)
{
	if (!FindTex(texName)) return -1;
	return find(texNames.begin(), texNames.end(), texName) - texNames.begin();
}

IDirect3DTexture9* dkm::Engine::GetTex(string texName)
{
	if (!FindTex(texName)) return NULL;
	return allTex[find(texNames.begin(), texNames.end(), texName) - texNames.begin()];
}

void dkm::Engine::CleanAllTex()
{
	std::vector<IDirect3DTexture9*>::iterator iter = allTex.begin();
	while (iter != allTex.end())
	{
		ReleaseCOM((*iter));

		++iter;
	}
}

